package com.my.user.util;

import com.my.entity.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DBUtil {
    private static final String URL="jdbc:mysql://localhost:3306/jsppro";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "12345678";
    public static Connection connection = null;
    public static PreparedStatement pst = null;
    public static ResultSet rs = null;

    public static void getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
    }

    public static void createdPreparedStatement(String sql,Object[] params) throws SQLException {
        pst = connection.prepareStatement(sql);
        if(params!=null){
            for(int i=0;i<params.length;i++){
                pst.setObject(i+1,params[i]);
            }
        }
    }

    public static void closeAll(ResultSet rs,Statement st,Connection conn){
        try{
            if(rs!=null) rs.close();
            if(st!=null) st.close();
            if(conn!=null) conn.close();
        }catch (SQLException e){
            e.printStackTrace();
        }
    }

    public static int getTotalCount(String sql){
        int count = -1;
        try{
            getConnection();
            createdPreparedStatement(sql,null);
            rs = pst.executeQuery();
            if(rs.next()){
                count = rs.getInt(1);
            }
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll(null,pst,connection);
        }
        return count;
    }


    public static boolean executeUpdate(String sql,Object[] params){
        try{
            getConnection();
            createdPreparedStatement(sql,params);
            int count = pst.executeUpdate();
            if(count>0){
                return true;
            }else{
                return false;
            }
        }catch (ClassNotFoundException e){
            e.printStackTrace();
            return false;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }finally {
            closeAll(null,pst,connection);
        }
    }

    public static ResultSet executeQuery(String sql,Object[] params){
        try{
            getConnection();
            createdPreparedStatement(sql,params);
            rs = pst.executeQuery();
            return rs;
        }catch (ClassNotFoundException e){
            e.printStackTrace();
            return rs;
        }catch (Exception e){
            e.printStackTrace();
            return rs;
        }
    }
}
